package com.uzhie.web.service;

import com.uzhie.exception.BussException;
import com.uzhie.jt808.msg.entity.JT_0800;
import com.uzhie.util.ConstantKit;
import com.uzhie.web.dao.PictureDAO;
import com.uzhie.web.module.Picture;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * Created by lilongfei on 2018/8/11.
 */
@Service
public class PictureService {


    @Autowired
    PictureDAO pictureDAO;
    @Autowired
    ConfigureService configureService;

    /**
     * 新增上传的图片资源
     *
     * @param vehicleNumber
     * @param order
     * @throws IOException
     */
    public void addPicture(String vehicleNumber, JT_0800 order) throws IOException {
        String path = configureService.readProperties().getJSONObject(ConstantKit.UPLOAD.getName()).getString(ConstantKit.UPLOAD.PIC.N());
        Picture picture = new Picture();
        picture.readFromOrder(vehicleNumber, path, order);
        pictureDAO.insert(picture);
    }

    /**
     * 查询图片资源
     *
     * @param vehicleNumber
     * @param startTime
     * @param endTime
     * @param warns
     * @return
     */
    public Map<String, List<Picture>> queryPicResByCondition(@NotEmpty(message = BussException.NOT_ISNULL) String vehicleNumber,
                                                             @NotEmpty(message = BussException.NOT_ISNULL) String startTime,
                                                             @NotEmpty(message = BussException.NOT_ISNULL) String endTime,
                                                             @NotEmpty(message = BussException.NOT_ISNULL) String warns) {
        if (warns.equals("-1")) warns = null;
        List<Picture> pictures = pictureDAO.queryListByConditions(vehicleNumber, startTime, endTime, warns);
        return buildGroup(pictures);
    }

    private Map<String, List<Picture>> buildGroup(List<Picture> pictures) {
        Map<String, List<Picture>> result = new HashMap<>();
        Collections.sort(pictures, Comparator.comparing(Picture::getShootingTime));
        for (Picture picture : pictures) {
            List<Picture> param = result.get(picture.getSimpleTime());
            if (param == null) {
                param = new ArrayList<>();
                result.put(picture.getSimpleTime(), param);
            }
            param.add(picture);
        }
        return result;
    }

    /**
     * 内部排序器
     */
    class MyCompare implements Comparator<Picture> {

        @Override
        public int compare(Picture o1, Picture o2) {
            if (o1.getShootingTime().getTime() < o2.getShootingTime().getTime()) {
                return 1;
            } else {
                return -1;
            }
        }

    }
}
